package org.zuel.boot.demo.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zuel.boot.demo.Dao.DemoPermMapper;
import org.zuel.boot.demo.Dao.DemoRolePermMapper;
import org.zuel.boot.demo.constant.AuthConstant;
import org.zuel.boot.demo.model.*;
import org.zuel.boot.demo.service.IPermService;
import org.zuel.boot.demo.util.ArgumentUtil;
import org.zuel.boot.demo.util.PinyinUtil;
import org.zuel.boot.demo.util.ResponseUtil;

import java.time.LocalDateTime;
import java.util.List;
@Service
public class PermService implements IPermService {

    private final DemoPermMapper permMapper;

    private final DemoRolePermMapper rolePermMapper;

    @Autowired
    public PermService(DemoPermMapper permMapper, DemoRolePermMapper rolePermMapper) {
        this.permMapper = permMapper;
        this.rolePermMapper = rolePermMapper;
    }

    @Override
    public Object list(String spellCode, String name, String con,
                       Integer page, Integer limit, String sort, String order) {
        if(limit != -1) {
            PageHelper.startPage(page, limit);
        }
        List<DemoPerm> models = permMapper
                .selectByExample(resolveCondition(spellCode, name, con, sort, order));
        long total = PageInfo.of(models).getTotal();
        return ResponseUtil.ok(total, models);
    }

    private DemoPermExample resolveCondition(String sepllCode, String name,
                                             String con, String sort, String order) {
        DemoPermExample example = new DemoPermExample();
        DemoPermExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if(!StringUtils.isEmpty(sepllCode)) {
            criteria.andSpellCodeLike("%" + sepllCode + "%");
        }
        if(!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(con)) {
            StringBuffer strCon = new StringBuffer();
            strCon.append("( upper(spell_code) like upper('%").append(con.trim()).append("%') ")
                    .append("or upper(name) like upper('%").append(con.trim())
                    .append("%')) ");
            criteria.addCriterion(strCon.toString());
        }
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        return example;
    }

    @Override
    public Object read(Integer id) {
        if(id == null) {
            return ResponseUtil.primaryKeyInvalid();
        }
        DemoPerm model = permMapper.selectByPrimaryKey(id);
        if(model == null) {
            return ResponseUtil.fail(AuthConstant.PERM_NOT_EXIST_CODE,
                    AuthConstant.PERM_NOT_EXIST_ERROR);
        }
        return ResponseUtil.ok(model);
    }

    @Override
    public Object add(DemoPerm model) {
        if(model == null ||
                !ArgumentUtil.notEmpty(model.getName(), model.getPermUrl(), model.getPermEl())) {
            return ResponseUtil.badArgument();
        }
        model.setSpellCode(PinyinUtil.getPinYinHeadChar(model.getName()));
        model.setAddTime(LocalDateTime.now());
        permMapper.insertSelective(model);
        return ResponseUtil.ok(permMapper.selectByPrimaryKey(model.getId()));
    }

    @Override
    public Object edit(DemoPerm model) {
        if(model == null || model.getId() == null) {
            return ResponseUtil.primaryKeyInvalid();
        }
        if(!ArgumentUtil.notEmpty(model.getName(), model.getPermUrl(), model.getPermEl())) {
            return ResponseUtil.badArgument();
        }
        model.setSpellCode(PinyinUtil.getPinYinHeadChar(model.getName()));
        model.setUpdateTime(LocalDateTime.now());
        permMapper.updateByPrimaryKeySelective(model);
        return ResponseUtil.ok(permMapper.selectByPrimaryKey(model.getId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object del(List<Integer> ids) {
        if(ids == null || ids.size() == 0) {
            return ResponseUtil.badArgument();
        }
        DemoPermExample example = new DemoPermExample();
        example.createCriteria().andDeletedEqualTo(false).andIdIn(ids);
        permMapper.logicalDeleteByExample(example);
        // 删除关系
        DemoRolePermExample mapExample = new DemoRolePermExample();
        mapExample.createCriteria().andDeletedEqualTo((byte) 0).andPermIdIn(ids);
        rolePermMapper.logicalDeleteByExample(mapExample);
        return ResponseUtil.ok();
    }
}
